<template>
  <div class="attach" style="height:450px;">
    <div class="content">
      <div class="projectFile" style="height:350px;overflow-y:auto;">
        <div class="attach-cls">
          <div class="upload-control" style="display: flex;">
            <ht-upload 
              class="upload-demo"
              multiple
              dbKey="Trd"
              :busField="changeId ? busField+'Change' : busField"
              :busKey="busKey"
              :busType="busType"
              ftpKey="ftp"
              v-model="attachList"
              :on-success="fileUploadSuccess" 
            >
              <el-button size="small" type="primary" style="height: 30px;width:85px;">
                <span style="font-size: 14px;">上传</span>
              </el-button>
            </ht-upload>
            <a-button type="primary" v-bind:disabled="!downloadAndView" @click="downLoadBatch" style="margin-left: 10px">下载</a-button>
            <a-button 
              v-if="!changeId"
              class="default"
              @click="deleteBatch"
              >删除</a-button
            >
          </div>
          <a-table
            :row-selection="{ selectedRowKeys: attachSelectedIds, onChange: doAttachSelected }"
            :columns="attachColumns"
            :data-source="attachDataList"
            bordered
            :pagination="false"
            >
             <template slot="name" slot-scope="text, record">
               <a @click="showAttach(record.key, record.uploader, record.name, true)">{{ record.name }}</a>
             </template>
          </a-table>
        </div>
      </div>
      <div class="btn">
        <a-button size="large" type="primary" @click="doClose()">关闭</a-button>
      </div>
    </div>
    
  </div>
</template>
<script>
import { getAction ,previewAttach} from '@/api/manage'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { endWith, formatFileSize } from '@/utils/common.js'
import '@/utils/upload.install.js'
import $ from 'jquery'
import Vue from 'vue'
const attachColumns = [
  {
    title: '附件名称',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '附件大小',
    dataIndex: 'size',
    width: '15%',
  },
  {
    title: '上传时间',
    dataIndex: 'time',
    width: '20%',
  },
  {
    title: '上传者',
    dataIndex: 'uploaderName',
    width: '20%',
  },
]

export default {
  props: {
    projectBuildId: {
      Type: String,
      default: '',
    },
    busKey: {
      Type: String,
      default: '',
    },
    busType: {
      Type: String,
      default: '',
    },
    busField: {
      Type: String,
      default: '',
    },
    changeId: {
      Type: Number,
      default: null
    },
    projectClass:{
      type:String,
      default:'',
    }
  },
  data() {
    return {
      attachList: [],
      attachDataList: [],
      attachColumns,
      attachSelectedIds: [], // Check here to configure the default column
      loading: false,
      attach: {
        getProjectBuildVOWithProjectManagers: '/projectBuild/getProjectBuildVOWithProjectManagers',
        getProjectBuildAttachCodeInfos: '/projectBuild/getProjectBuildAttachCodeInfos',
        downLoadBatch: '/common/downLoadBatch',
        deleteBatch: '/common/deleteBatch',
        getAttachInfo: '/tp/attach/getAttaches',
        logAttachAdd: '/projectChange/logAttachAdd',
      },
      canEdit: false,
      downloadAndView: false,
      delAttachIds: []

    }
  },
  mounted() {
    this.initData()
  },
  computed: {},
  watch: {
    attachList: function () {
      this.attachDataListFresh()
    },
  },
  methods: {
    doClose(){
      this.$emit('closeAttachModal')
    },
    fileUploadSuccess(response, file, fileList) {
      debugger
      if(!this.changeId){
        return;
      }
      //项目变更，记录附件变更日志
      var res=response[0];
      var data={
        busKey:res.busKey,
        busType:res.busType,
        fileName:res.fileName ,
        changeTarget:4
      }
      getAction(this.attach.logAttachAdd, data)
      .then((res) => {
        if (res.code == 200) {
          console.log('团队部门附件记录日志成功:'+res.fileName)
        } else {
          this.$message.warning('团队部门附件记录附件变更日志失败:' + res.msg)
        }
      })
      .catch((res) => {
        this.$message.warning('其他附件记录附件变更日志异常:' + res.msg)
      })
    },
    showAttach(id, uploader, fileName, autoDownload) {
      if (!this.checkDowloadAndViewPermisson(uploader)) {
        this.$message.warning('仅有该附件上传人、审批人、抄送人、项目经理、副经理可以查看!')
        return
      }
      //以rar、zip、dwg结尾的文件，直接下载不预览
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        if (autoDownload) {
          this.doDownLoadBatch(id)
          return
        }
        this.$message.warning('该附件类型不支持预览，请下载附件查看')
        return
      }

      let params={
        id:id,
        ftpKey:'ftp'
      };
      previewAttach(params).then(result=>{
        const url=URL.createObjectURL(result)
        if (this.projectClass == '40' || this.projectClass == '61') {
          window.open(process.env.BASE_URL+'/pdf/web/normalViewer.html?file=' + url)
        } else {
          window.open(process.env.BASE_URL+'/pdf/web/viewer.html?file=' + url)
        }
      }).catch(err => {
        this.$message.warning('下载文件失败');
      })
    },
    checkDowloadAndViewPermisson(uploader) {
      var currUser = Vue.ls.get(USER_INFO).username
      if (uploader == currUser || this.downloadAndView) {
        return true
      }
      return false
    },
    attachDataListFresh() {
      this.attachDataList = []
      debugger
      this.attachList.forEach((item) => {
        var flag = true
        this.delAttachIds.forEach((delId) => {
          if (item.id == delId) {
            flag = false
          }
        })
        if (flag) {
          var size = formatFileSize(item.size)
          this.attachDataList.push({
            key: item.id,
            name: item.fileName,
            size: size,
            time: item.uploadTime,
            uploader: item.uploader,
            uploaderName: item.uploaderName,
          })
        }
      })
    },
    start() {
      this.loading = true
      setTimeout(() => {
        this.loading = false
        this.attachSelectedIds = []
      }, 1000)
    },
    doAttachSelected(selectedRowKeys) {
      this.attachSelectedIds = selectedRowKeys
    },
    doDownLoadBatch(attachIds) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame')
      var href =
        this.API_BASE_URL +
        this.attach.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        Vue.ls.get(ACCESS_TOKEN)
      iframe.src = href
    },
    downLoadBatch() {
      if (this.attachSelectedIds != null && this.attachSelectedIds.length > 0) {
        this.doDownLoadBatch(this.attachSelectedIds)
      } else {
        this.$message.warning('请选择要下载的其它附件')
      }
    },
    deleteBatch() {
      if (this.attachSelectedIds != null && this.attachSelectedIds.length > 0) {
        getAction(this.attach.deleteBatch, {
          attachIds: this.attachSelectedIds.join(','),
          dbKey: 'Trd',
          ftpKey: 'ftp',
          changeId: this.changeId,
          changeTarget: 4
        }).then((res) => {
            if (res.code == 1) {
              this.delAttachIds = this.delAttachIds.concat(this.attachSelectedIds)
              this.attachDataListFresh()
              this.attachSelectedIds=[]
              this.$message.success('批量删除成功', 2)
            } else {
              this.$message.warning('批量删除失败:' + res.msg, 2)
            }
          })
          .catch((res) => {
            this.$message.warning('批量删除失败:' + res.msg)
          })
      } else {
        this.$message.warning('请选择要删除的其它附件')
      }
    },
    initData() {
      var vm = this
      getAction(this.attach.getProjectBuildVOWithProjectManagers, { id: this.projectBuildId })
        .then((res) => {
          if (res.code == 200) {
            var result = res.result
            if (result != null) {
              vm.projectBuild = result
              if (result.projectType != null && result.projectType.length > 0) {
                var currUser = Vue.ls.get(USER_INFO).username
                if (
                  vm.projectBuild.createUserId === currUser ||
                  vm.projectBuild.currentAuditUserId === currUser ||
                  (vm.projectBuild.copyForUserIds != null && vm.projectBuild.copyForUserIds.indexOf(currUser) > -1) ||
                  (vm.projectBuild.allAuditors != null && vm.projectBuild.allAuditors.indexOf(currUser) > -1) ||
                  (vm.projectBuild.projectManagers != null && vm.projectBuild.projectManagers.indexOf(currUser) > -1) ||
                  (vm.projectBuild.assistantProjectManagers != null &&
                    vm.projectBuild.assistantProjectManagers.indexOf(currUser) > -1)
                ) {
                  vm.canEdit = true
                }
                //变更
                if(this.canEdit && this.changeId){
                  vm.canEdit = true
                }
                if (vm.canEdit || vm.projectBuild.downAndView) {
                  vm.downloadAndView = true
                }
              }
            }
          } else {
            this.$message.warning('查询附件相关信息失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询附件相关信息异常:' + res.message)
        })
    },
  },
}
</script>
<style lang="less" scoped>
/deep/.el-upload-list {
  display: none;
}
/deep/.anticon {
  font-size: 16px;
  vertical-align: middle;
}
/deep/ .ant-btn-primary {
  width: 85px;
  height: 30px;
  border-radius: 2px;
  background: #1890ff;
  margin-right: 10px;
}
/deep/ .default {
  width: 85px;
  height: 30px;
  border-radius: 2px;
}
/deep/ .ant-table-thead > tr > th {
  background: #dadee9 !important;
}
/deep/.ant-table-thead > tr:first-child > th:first-child,
/deep/ .ant-table table {
  border-radius: unset;
  line-height: 1;
}
/deep/ .ant-table-tbody .ant-table-row td {
  &:nth-child(2) {
    color: #3e8ee2;
  }
}
/deep/ .ant-table-tbody .ant-table-row td {
  padding-top: 8px;
  padding-bottom: 8px;
}
.attach {
  border: 1px solid #e6e6e6;
  background-color: #fff;
  padding-bottom: 30px;
  .header {
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    padding: 20px 0 0 20px;
  }
  .content {
    padding: 15px;
    .projectFile {
      .title {
        border-left: 3px solid #47a4fa;
        padding: 0 10px;
        .download-control {
          display: inline-block;
          margin-left: 10px;
        }
      }
    }
    ul {
      list-style: none;
      padding: 15px 0;
      border-bottom: 1px solid #f7f7f7;
      li {
        padding: 15px !important;
        border: 1px solid #e8e8e8;
        border-radius: 6px;
        margin-bottom: 15px;
        display: flex;
        align-items: flex-start;
      }
      .upload-demo {
        display: flex;
        /deep/ .el-upload {
          margin-right: 10px;
        }
      }
    }
    .attach-cls {
      .upload-control {
        margin-bottom: 15px;
      }
    }
    .btn {
      display: flex;
      justify-content: center;
      margin-top: 30px;
    }
  }
}
</style>